package ldh.im.fxgui.service;

import javafx.application.Platform;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.status.ImMessageFileStatus;
import ldh.im.fxbase.util.FxThreadUtil;
import ldh.im.fxgui.component.message.bo.WrapImMessage;
import ldh.im.fxgui.component.message.bo.WrapImMessageStatus;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.listener.FileProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultFileProgressListener implements FileProgressListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultFileProgressListener.class);

    @Override
    public void progress(Long sessionId, String fileServiceId, long total, long size) {
        LOGGER.info("file progress, fileId: {}, total: {}, size: {}", fileServiceId, total, size);
        WrapImMessage wrapImMessage = UiUtil.getWrapImMessage(sessionId, fileServiceId);
        if (wrapImMessage != null) {
            LOGGER.info("file progress and update ui, fileId: {}, total: {}, size: {}", fileServiceId, total, size);
            FxThreadUtil.runLater(()->{
                wrapImMessage.isProgressProperty().set(true);
                wrapImMessage.progressProperty().set((size * 1.0/total));
                ImMessage message = wrapImMessage.getImMessage();
                if (message.getCurrentUserId().equals(message.getFromUserId())) { // 发送者
                    wrapImMessage.setStatusProperty(WrapImMessageStatus.uploading);
                } else { // 接受者
                    wrapImMessage.setStatusProperty(WrapImMessageStatus.downloading);
                }
                if (total == size) {
                    wrapImMessage.isProgressProperty().set(true);
                    UiUtil.deleteCacheWrapImMessage(fileServiceId);

                    if (message.getCurrentUserId().equals(message.getFromUserId())) { // 发送者
                        wrapImMessage.getImMessage().setFileStatus(ImMessageFileStatus.uploaded);
                        UiUtil.uiUpdateMessage(wrapImMessage.getImMessage());
                    } else { // 接受者
                        wrapImMessage.getImMessage().setFileStatus(ImMessageFileStatus.downloaded);
                        UiUtil.uiUpdateMessage(wrapImMessage.getImMessage());
                    }
                }
            });
        }
    }
}
